//
//  ZTXQViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/8/3.
//  Copyright © 2016年 ZhiYu Hao. All rights reserved.
//

#import "ZTXQViewController.h"
#import "YXScrollowActionSheet.h"
#import "XiangQingViewController.h"
#import "WebCell.h"
#import "HomeViewZuoPinCell.h"
#import "IWTextView.h"
#import "IGZTXQApi.h"
#import "IGiGalleryListApi.h"
#import "IGArtWorkModel.h"
#import "IGCommentBean.h"
#import "IGTopicDetailCommentCell.h"
#import "IGCommentApi.h"
#import "IGSpecial.h"
#import "NotFindDeviceView.h"
#import "IGiGalleryPushApi.h"
#import "IGPushiGalleryListVC.h"
#import "IGMyiGalleryVC.h"
@interface ZTXQViewController () <UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate, UITextViewDelegate>
{
    BOOL isRecomment;
    BOOL isTop;
    CGRect selRect;
    CGFloat currtOff;
    UIView *imView;
}
@property (nonatomic, assign) CGFloat fittHeight;
@property (nonatomic, strong) NotFindDeviceView *findView;

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic, strong) NSMutableDictionary *heightDic;//计算webview的高度
@property (nonatomic, strong) WebCell *webCell;
@property (nonatomic, copy) NSString *pageNum;
@property (nonatomic, copy) NSString *pageSize;
@property (nonatomic, strong) IGZTXQApi *api;
@property (nonatomic, strong) IGSpecial *special;//专题模型
@property (nonatomic, strong) NSMutableArray *commentMuArr;//评论列表
@property (nonatomic, strong) NSArray *productArr;//作品列表
@property (nonatomic, strong) NSArray *iGalleryListArr;
@property (nonatomic, strong) IGiGalleryListApi *iGListApi;
@property (nonatomic, strong) IGCommentApi *commentApi;
@property (nonatomic, strong) IGCommentBean *replayTheSeletedCellModel;
@end

@implementation ZTXQViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"专题";
    self.title = NSLocalizedString(@"Feature", nil);
    self.heightDic = [[NSMutableDictionary alloc] init];

    [self ig_setupRightButtonItemWithTitle:nil image:[UIImage imageNamed:@"share_btn"] highLightedImage:[UIImage imageNamed:@"share_btn"]];
    @KWeakObj(self)

    [self.table registerClass:[HomeViewZuoPinCell class] forCellReuseIdentifier:@"HomeViewZuoPinCell"];
    self.table.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.table ig_setHeaderWithRefreshingBlock:^{
        selfWeak.pageSize = @"10";
        selfWeak.pageNum = @"1";
        [selfWeak loadData];
    }];
    
    self.webCell = [[WebCell alloc] init];
    _fittHeight = 0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    _pageSize = @"10";
    _pageNum = @"1";
    self.api = [IGZTXQApi new];
    self.special = [IGSpecial new];
    self.commentMuArr = [@[] mutableCopy];
    self.productArr = [NSArray array];
    self.commentApi = [IGCommentApi new];
    [self loadData];
}

- (void)iGalleryBingRequest
{
    self.iGListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    __weak typeof(self) weakSelf = self;
    [self.iGListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model = resp.data;
            weakSelf.iGalleryListArr = [NSArray arrayWithArray:model.equs];
        }
    }];
}

- (void)pushToDev:(IGArtWorkModel *)model
{
    IGiGalleryEqu *equ = self.iGalleryListArr[0];
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:@[equ.macId] pIds:@[model.aId]];
//    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    @KWeakObj(self)
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
//            [selfWeak presentMessageTips:@"推送成功..."];
            [selfWeak presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
        }
    }];
}

- (void)loadData
{
    self.api.pageSize = _pageSize;
    self.api.pageNum = _pageNum;
    self.api.aId = _s_id;
    @KWeakObj(self)
    [self.api startWithDecodeClass:[IGZTXQResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [selfWeak.table ig_endFooterRefreshing];
        [selfWeak.table ig_endHeaderRefreshing];
        if (responseObject)
        {
            IGZTXQResp *resp = responseObject;
            IGZTXQModel *model = resp.data;
            
            NSMutableArray *arr = model.comments;
            if (arr && [arr count] > 0)
            {
                [selfWeak setupFooter];
            }
            else
            {
                [selfWeak.table ig_endFooterRefreshingWithNoMoreData];
            }
            if ([selfWeak.pageNum isEqualToString:@"1"])
            {
                selfWeak.commentMuArr = [NSMutableArray arrayWithArray:arr];
                selfWeak.special = model.special;
                selfWeak.productArr = model.products;
            }
            else
            {
                [selfWeak.commentMuArr addObjectsFromArray:arr];
            }
            selfWeak.webCell.htmlUrl = [NSString stringWithFormat:@"%@&source=app", selfWeak.special.content];
            [selfWeak.table reloadData];
        }
    }];
}

- (void)commitCommentRequest
{
    __weak typeof(self) weakSelf = self;
    [self.commentApi startWithDecodeClass:[IGCommentResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGCommentResp *resp = responseObject;
            IGCommentModel *model = resp.data;
            IGCommentBean *commentModel = model.comment;
            [weakSelf.commentMuArr replaceObjectAtIndex:0 withObject:commentModel];
        } else {
            [weakSelf.commentMuArr removeObjectAtIndex:0];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.table reloadData];
        });
    }];
}

- (void)setupFooter
{
    @KWeakObj(self)
    [self.table ig_setFooterWithRefreshingBlock:^{
        selfWeak.pageNum = [NSString stringWithFormat:@"%ld", [selfWeak.pageNum integerValue] + 1];
        [selfWeak loadData];
    }];
}

#pragma mark — UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    return _special ? 4 : 0;
    if (_special)
    {
        return _fittHeight > 0 ? 4 : 1;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    if (section == 1)
    {
        return _productArr.count ?: 0;
    }
    if (section == 2)
    {
        return 1;
    }
    if (section == 3)
    {
        return self.commentMuArr.count?:0;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = [UIColor grayColor];
    cell.clipsToBounds = YES;
    CGFloat h = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    @KWeakObj(self)
    if (indexPath.section == 0)
    {
        WebCell *cell;
        cell = self.webCell;
        cell.webCellReturnHeightBlock = ^(WebCell *__weak webCell,CGFloat height){
            if (selfWeak.fittHeight == 0 || selfWeak.fittHeight < height)
            {
                selfWeak.fittHeight = height;
                [selfWeak.table reloadData];
            }
        };
        return cell;
    }
    else if (indexPath.section == 1)
    {
        HomeViewZuoPinCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeViewZuoPinCell" forIndexPath:indexPath];
        IGArtWorkModel *model = _productArr[indexPath.row];
        cell.recommendDetail = model;
        cell.pushBlock = ^{
            /*
             1、没有绑定设备——引导用户绑定设备
             2、绑定一台设备——直接推送
             3、绑定多台设备——跳转到选择设备列表
             */
            selfWeak.iGListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
            [selfWeak.iGListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                if (responseObject)
                {
                    IGiGalleryListResp *resp = responseObject;
                    IGiGalleryListModel *model1 = resp.data;
                    selfWeak.iGalleryListArr = [NSArray arrayWithArray:model1.equs];
                    if (selfWeak.iGalleryListArr.count == 0) {
                        selfWeak.findView = [NotFindDeviceView showNotFindDeviceView];
                        selfWeak.findView.bangdingBlock = ^{
                            [UIViewController ig_pushViewControllerClass:[IGMyiGalleryVC class] animated:YES];
                        };
                    } else if (selfWeak.iGalleryListArr.count == 1) {
                        [selfWeak pushToDev:model];
                    } else {
                        IGPushiGalleryListVC *listVC = [[IGPushiGalleryListVC alloc] initWithType:IGPushiGalleryType1N];
                        listVC.recommend = model;
                        [UIViewController ig_pushViewController:listVC animated:YES];
                    }
                }
            }];
            
            
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 2)
    {
        UIImageView *msg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 25, 25)];
        msg.image = [UIImage imageNamed:@"home_dian"];
        msg.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:msg];
        msg.centerY = h/2;
        
        UILabel *place = [[UILabel alloc] initWithFrame:CGRectZero];
//        place.text = @"艺术大家谈，我来说两句...";
        place.text = NSLocalizedString(@"Comments", nil);
        place.textColor = [UIColor lightGrayColor];
        place.font = [UIFont systemFontOfSize:15];
        [cell.contentView addSubview:place];
        [place sizeToFit];
        place.x = msg.right+5;
        place.height = h;
    }
    else if (indexPath.section == 3)
    {
        cell = [IGTopicDetailCommentCell cellWithTableView:tableView];
        IGCommentBean *model = [self.commentMuArr objectAtIndex:indexPath.row];
        [(IGTopicDetailCommentCell *)cell configCellWithModel:model];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        IGArtWorkModel *base = _productArr[indexPath.row];
        XiangQingViewController *vc = [[XiangQingViewController alloc] init];
        vc.p_id = base.aId;
        vc.isRoot = YES;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
    if (indexPath.section >= 2)
    {
        isRecomment = indexPath.section != 2;
        if (indexPath.section > 2)
        {
            _replayTheSeletedCellModel = self.commentMuArr[indexPath.row];
        } else {
            _replayTheSeletedCellModel = nil;
        }
        
        NSString *placeholder;
        currtOff = tableView.contentOffset.y;
        selRect = [tableView rectForRowAtIndexPath:indexPath];
        if (indexPath.section == 2)
        {
            isTop = YES;
//            placeholder = @"艺术大家谈，我来说两句...";
            placeholder = NSLocalizedString(@"comment", nil);

        }
        else
        {
            isTop = NO;
            IGCommentBean *commentInfo = self.commentMuArr[indexPath.row];
            placeholder = [NSString stringWithFormat:@"@%@:",commentInfo.commentUserNick];
        }
        if (!imView)
        {
            imView = [[UIView alloc] initWithFrame:CGRectMake(0, KSCREENHEIGHT, KSCREENWIDTH, 50)];
            [self.view addSubview:imView];
            imView.backgroundColor = [UIColor whiteColor];
            
            UIImageView *msg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 25, 25)];
            msg.image = [UIImage imageNamed:@"home_dian"];
            msg.contentMode = UIViewContentModeScaleAspectFit;
            [imView addSubview:msg];
            msg.centerY = imView.height/2;
            
            IWTextView *imText = [[IWTextView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 50)];
            imText.width = imView.width-msg.right-5;
//            imText.placeholder = @"艺术大家谈，我来说两句...";
            imText.placeholder = NSLocalizedString(@"comment", nil);
            imText.contentInset = UIEdgeInsetsMake(7, 0, 7, 0);
            imText.font = [UIFont systemFontOfSize:15];
            imText.delegate = self;
            imText.returnKeyType = UIReturnKeySend;
            imText.tag = 80;
            imText.x = msg.right+5;
            [imView addSubview:imText];
        }
        IWTextView *imText = [imView viewWithTag:80];
        if (imText.isFirstResponder)
        {
            [self check:selRect];
        }
        [imText becomeFirstResponder];
        imText.placeholder = placeholder;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0 || section == 1)
    {
        return 10;
    }
    return 0.1f;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return _fittHeight == 0 ? 30 : _fittHeight;
    }
    else if (indexPath.section == 1)
    {
        IGArtWorkModel *detail = _productArr[indexPath.row];
        if ([detail.plates intValue] == 1)
        {
            return 275;
        }
        else
        {
            return 430;
        }
    }
    else if (indexPath.section == 2)
    {
        return 50;
    }
    else if (indexPath.section == 3)
    {
        IGCommentBean *model = [self.commentMuArr objectAtIndex:indexPath.row];
        CGFloat cell_height = [IGTopicDetailCommentCell hyb_heightForTableView:self.table config:^(UITableViewCell *sourceCell) {
            IGTopicDetailCommentCell *cell = (IGTopicDetailCommentCell *)sourceCell;
            [cell configCellWithModel:model];
        } cache:^NSDictionary *{
            NSDictionary *cache = @{kHYBCacheUniqueKey : [NSString stringWithFormat:@"k%@", model.commentId],
                                    kHYBCacheStateKey : @"",
                                    kHYBRecalculateForStateKey : @(YES)};
            model.shouldUpdateCache = NO;
            return cache;
        }];
        cell_height += 15;
        return cell_height;
    }
    return 0;
}

#pragma mark === 分享
- (void)ig_rightButtonPressed:(id)sender
{
    YXScrollowActionSheet *cusSheet = [[YXScrollowActionSheet alloc] init];
    IGShareModel *shareModel = [_special getShareModel];
    cusSheet.shareModel = shareModel;
    [cusSheet show];
}

- (void)keyboardChangeFrame:(NSNotification *)not
{
    IWTextView *imText = [imView viewWithTag:80];
    imView.hidden = NO;
    CGRect beg = [not.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect end = [not.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    imView.bottom = beg.origin.y;
    BOOL hid = NO;
    if (end.origin.y==KSCREENHEIGHT)
    {
        hid = YES;
    }
    [UIView animateWithDuration:[not.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        if (hid)
        {
            imView.top = end.origin.y;
        }
        else
        {
            imView.bottom = end.origin.y;
        }
    } completion:^(BOOL finished)
     {
        if (!imText.isFirstResponder)
        {
            imView.hidden = YES;
        }
    }];
}

- (void)keyboardShow:(NSNotification *)not
{
    CGRect end = [not.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat h = end.origin.y-50;
    CGFloat value = selRect.origin.y-currtOff;
    CGFloat of = h-value;
    [UIView animateWithDuration:.2 animations:^{
        if (isTop)
        {
            [self.table setContentOffset:CGPointMake(0, currtOff-of)];
        }
        else
        {
            [self.table setContentOffset:CGPointMake(0, currtOff-of+selRect.size.height)];
        }
    }];
}

- (void)check:(CGRect)rect
{
    CGFloat h = imView.y;
    CGFloat value = rect.origin.y-currtOff;
    CGFloat of = h-value;
    [UIView animateWithDuration:.2 animations:^{
        if (isTop)
        {
            [self.table setContentOffset:CGPointMake(0, currtOff-of)];
        }
        else
        {
            [self.table setContentOffset:CGPointMake(0, currtOff-of+selRect.size.height)];
        }
    }];
}

- (void)keyboardHide:(NSNotification *)not
{
    [self.table setContentOffset:CGPointMake(0, currtOff)];
}

#pragma mark - 发表评论
- (void)sendAcion {
    IWTextView *imText = [imView viewWithTag:80];
    if (imText.text.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Add your comments", nil)];
        return;
    }
    
    if (imText.text.length > 300) {
        [self presentMessageTips:NSLocalizedString(@"Exceeding max word count. Input Not Available", nil)];
        
        return;
    }
    
    IGCommentType commentType = IGCommentTypeFirst;
    if (self.replayTheSeletedCellModel) {
        commentType = IGCommentTypeSecond;
    }
    
    //创建一个新的CommentModel,并给相应的属性赋值，然后加到评论数组的最后，reloadData
    IGCommentBean *commentModel = [[IGCommentBean alloc]init];
    commentModel.commentUserNick = [IGUser getNike];
    commentModel.commentUserId = [IGUser getUid];
    commentModel.commentUserAvater = [IGUser getImage];
    commentModel.parentCommentUserNick = (commentType == IGCommentTypeSecond)?self.replayTheSeletedCellModel.commentUserNick:@"";
    commentModel.parentCommentUserId = (commentType == IGCommentTypeSecond)?self.replayTheSeletedCellModel.commentUserId:@"";
    commentModel.content = imText.text;
    commentModel.shouldUpdateCache = YES;
    [self.commentMuArr insertObject:commentModel atIndex:0];
    [self.table reloadData];
    
    //提交数据==>若失败刷新界面
    self.commentApi.pid = _special.sid;
    self.commentApi.parentType = IGParentTypeSubject;
    self.commentApi.content = commentModel.content;
    self.commentApi.commentType = commentType;
    if (commentType == IGCommentTypeFirst) {
        self.commentApi.parentUid = _special.sid;
        self.commentApi.cId = @"";
    } else {
        self.commentApi.parentUid = self.replayTheSeletedCellModel.commentUserId;
        self.commentApi.cId = self.replayTheSeletedCellModel.commentId;
    }
    
    [self commitCommentRequest];
    
    imText.text = nil;
    [self.view endEditing:YES];
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (![textView isKindOfClass:[IWTextView class]])
    {
        return NO;
    }
    if ([text isEqualToString:@"\n"])
    {
        [self sendAcion];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (![textView isKindOfClass:[IWTextView class]])
    {
        return;
    }
    UITextRange *markedRange = [textView markedTextRange];
    if (markedRange)
    {
        return;
    }
    if (textView.text.length > 50)
    {
//        [self presentMessageTips:@"最多可输入50个字"];
        [self presentMessageTips:NSLocalizedString(@"No more than 50 characters.", nil)];
        NSRange range = [textView.text rangeOfComposedCharacterSequenceAtIndex:50];
        textView.text = [textView.text substringToIndex:range.location];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
